package com.qf.driver.service.impl;

import com.qf.common.constant.CommonConstant;
import com.qf.common.dto.DeviceDataDto;
import com.qf.common.model.DeviceModelValue;
import com.qf.common.sdk.bean.MqttMessage;
import com.qf.common.utils.JsonUtil;
import com.qf.driver.service.MqttReciveService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author 千锋健哥
 */
@Slf4j
@Service
public class MqttReciveServiceImpl implements MqttReciveService {

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Override
    public void reciveValue(MqttMessage mqttMessage) {
        //1. 判断消息不为空
        if (mqttMessage != null) {
            //2. 获取主题topic
            String topicName = mqttMessage.getMessageHeader().getMqttReceivedTopic();
            //3. 判断是传感器上报给平台的topic主题数据
            if (topicName.contains("/qfjava/device/data")) {
                //获取消息载荷具体内容, 也就是内容数据
                String payload = mqttMessage.getMessagePayload().getPayload();
                try {
                    //4. 数据封装初始化
                    DeviceDataDto deviceDataDto = JsonUtil.parseObject(payload, DeviceDataDto.class);
                    if (deviceDataDto != null) {
                        DeviceModelValue deviceModelValue = new DeviceModelValue();
                        deviceModelValue.setCreateTime(new Date());
                        //产品key
                        deviceModelValue.setProduct_key(deviceDataDto.getProduct_key());
                        //设备key
                        deviceModelValue.setDevice(deviceDataDto.getDevice());
                        //租户id
                        deviceModelValue.setTenant_id(deviceDataDto.getTenant_id());
                        //传感器是上报的数据
                        deviceModelValue.setData(deviceDataDto.getData());

                        //5. 将数据发给rabbitmq消息中间件
                        //第一个参数是交换器名字, 第二个参数路由键名字, 第三个参数是发送的数据
                        rabbitTemplate.convertAndSend(CommonConstant.Rabbit.TOPIC_EXCHANGE_VALUE,
                                CommonConstant.Rabbit.ROUTING_DEVICE_VALUE_PREFIX + "data",
                                deviceModelValue);
                    }
                } catch (Exception e) {
                    log.info("qf-driver-mqtt设备中心数据异常, 传感器数据格式不符合要求:" + payload);
                }
            }
        } else {
            log.info("消息为空: " + mqttMessage);
        }
    }

}
